<template>
  <div class="photo-item">
    <img
      ref="imgRef"
      :src="setUrl"
      class="photo"
      :style="loaded ? { opacity: 1 } : { opacity: 0, height: '0' }"
      @load="handleLoad"
      @error="handleError"
    />
    <img
      v-if="!loaded"
      :src="placeholderImage"
      :style="loaded ? { opacity: 0 } : { opacity: 1, marginTop: '-20px' }"
      class="photo imgloading"
    />
    <!-- marginTop 是hack，为了抵消img标签本身的占位 -->
  </div>
</template>

<script setup>
// 
import imgPlaceHolder from "@/assets/imgPlaceHolder.jpg"
const props = defineProps({
  url: {
    type: String,
    required: true,
  },
  alt: {
    type: String,
    default: "Photo",
  },
  placeholderImage: {
    type: String,
    default: imgPlaceHolder, // 更新为你的占位图片路径
  },
})

const loaded = ref(false)
const imgRef = ref(null)
const setUrl = ref("")
// 加载成功后的处理函数
const handleLoad = () => {
  setTimeout(() => {
    loaded.value = true
  }, 50)
}

// 加载错误后的处理函数
const handleError = () => {
  loaded.value = false // 可以在这里处理加载错误情况，比如设置为占位图
}

const observerCallback = (entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      console.log("[ isIntersecting ]-56")
      setUrl.value = props.url
      // const index = entry.target.getAttribute('data-index');
      // loadImage(index);
      observer.unobserve(entry.target)
    }
  })
}
const observer = new IntersectionObserver(observerCallback, { threshold: 0 })

onMounted(() => {
  observer.observe(imgRef.value)
})
</script>

<style scoped>
.photo-item {
  position: relative;
  overflow: hidden;
  width: 100%;
}

.photo {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保持图片比例 */
  transition: opacity 0.5s ease;
}

.imgloading {
  opacity: 0.5; /* 给占位图一个轻微的透明度 */
}
</style>
